<script setup>
import {defineEmits, defineProps, ref} from "vue";
import {ElMessage} from "element-plus";

const defaultImg = require("@/assets/img/default-img.png")
const headers = ref({
  Authorization: localStorage.getItem("account")
})
const props = defineProps({
  "uploadId": {
    type: Object,
    default:()=>{return {}}
  },
  "file_name": {type: String, default: "upload"},
  "showFileList": {
    type: Boolean,
    default: true
  },
  "uploadPath": {
    type: String
  },
  "rule": {type: String},
  "tips": {
    type: String
  },
  "imageUrl": {
    type: String,
    // default: ()=>defaultImg.va/ue
  },
  "imageCls": {
    type: String,
  },
  "size": {
    type: Number,
    default: 0
  },
  "fileList": {
    type: Array || Boolean,
    default: []
  },
  "multiple": {
    type: Boolean,
    default: false
  },
  "uploadBtn": {
    type: String,
    default: "image"
  }
})
const emit = defineEmits(["uploadSuccess"])
const upload_success = (response, file) => {
  if (response.errCode !== 0 || Object.keys(response.result).length < 1) {
    return ElMessage.error(response.errMsg)
  }
  emit('uploadSuccess', {result: response.result, file})
}

const before_upload = (file)=>{
  if(props.rule){
    let reg = new RegExp(props.rule);
    if (!reg.test(file.type)) {
      ElMessage.error("上传文件资源不符合指定文件类型！");
      return false;
    }
  }

  if (props.size > 0 && props.size < file.size) {
    ElMessage.error("上传文件资源过大！");
    return false;
  }
}

const err_upload = ()=>{
  ElMessage.error("上传文件失败！");
}
</script>

<template>
  <el-upload :action="props.uploadPath"
             :data="props.uploadId"
             :on-success="upload_success"
             :name="props.file_name"
             :show-file-list="props.showFileList"
             :before-upload="before_upload"
             :file-list="props.fileList"
             :multiple="props.multiple"
             :on-error="err_upload"
             :headers="headers">
    <el-image :src="props.imageUrl" :class="props.imageCls" fit="contain" v-if="props.uploadBtn === 'image'">
      <template #placeholder>
        <el-image :src="defaultImg" fit="contain"></el-image>
      </template>
      <template #error>
        <el-image :src="defaultImg" fit="contain"></el-image>
      </template>
    </el-image>
    <el-button v-else plain icon="upload">点击上传</el-button>
    <template #tip>
      <div v-if="props.tips">
        <el-text type="info">{{ props.tips }}</el-text>
      </div>
    </template>
  </el-upload>
</template>

<style scoped lang="less">
.avatar {
  img {
    width: 45px;
  }
}

.vea-upload-icon {
  width: 60px;
}

.vea-upload-max220 {
  width: 110px !important;

  img {
    width: 110px !important;
  }
}

.vea-upload-max100{
  width: 50px !important;
}
</style>
